package com.cjjd.c.feature.subscribe.change_order;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.TextView;

import com.cjjd.c.R;
import com.cjjd.c.ShareKeys;
import com.cjjd.c.base.ActionBarActivity;
import com.cjjd.c.bean.HttpResult;
import com.cjjd.c.bean.ListResult;
import com.cjjd.c.bean.subscribe.ChangeOrderBean;
import com.cjjd.c.bean.subscribe.DiffAmountBean;
import com.cjjd.c.bean.subscribe.HotelRoomShowModel;
import com.cjjd.c.bean.subscribe.SaveOrderChangeBean;
import com.cjjd.c.feature.home.chekin.checklist_detail.CheckinDetailActivity;
import com.cjjd.c.feature.home.chekin.pay.PayPledgeActivity;
import com.cjjd.c.feature.subscribe.info.HotelDetailExpandableListAdapter;
import com.cjjd.c.http.CallbackImpl;
import com.cjjd.c.http.JsonUtils;
import com.cjjd.c.utils.LogUtil;
import com.cjjd.c.utils.SharePrefUtil;
import com.cjjd.c.utils.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

/**
 * ----------------------------------
 * Created by xyd on 2017/11/30.
 * <p/>
 * 描  述：修改订单
 * <p/>
 * 修订历史:
 * ----------------------------------
 */

public class ChangeOrderActivity extends ActionBarActivity {


    @Bind(R.id.tv_hotel_name)
    TextView tvHotelName;
    @Bind(R.id.tv_time_for_settle_leave)
    TextView tvTimeForSettleLeave;
    @Bind(R.id.tv_hotel_style)
    TextView tvHotelStyle;
    @Bind(R.id.tv_order_id)
    TextView tvOrderId;
    @Bind(R.id.tv_order_price)
    TextView tvOrderPrice;

    @Bind(R.id.tv_live_time)
    TextView tvLiveTime;
    @Bind(R.id.tv_live_weekday)
    TextView tvLiveWeekday;
    @Bind(R.id.tv_leave_time)
    TextView tvLeaveTime;
    @Bind(R.id.tv_leave_weekday)
    TextView tvLeaveWeekday;

    @Bind(R.id.el_rooms)
    ExpandableListView elRooms;

    @Bind(R.id.btn_next)
    Button btnNext;

    private ArrayList<HotelRoomShowModel> groupTittles;
    private ArrayList<ArrayList<HotelRoomShowModel.HotelRoomTypeShowModel>> groupDatas;
    private HotelDetailExpandableListAdapter selectHomeExpandableListAdapter;


    private String orderMainUuid;
    private ChangeOrderBean changeOrderBean;

    private double diffAmount = -1;

    /**
     * 0 支付差价；  1 直接修改
     */
    private int PayOrChange = -1;

    @Override
    public Object getTitleString() {
        return "修改订单";
    }

    @Override
    public int getContentView() {
        return R.layout.activity_change_order;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        orderMainUuid = getIntent().getStringExtra("orderMainUuid");

        toChangeBookOrder();

        initView();
    }

    /**
     * 获取酒店可售房间列表
     *
     * @param hotelUuid
     */
    private void getHotelAvailableRoomTypeList(String hotelUuid) {
        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("hotelUuid", hotelUuid);    //先写死
        h1.put("startDate", "2017-12-21");    //开始时间
        h1.put("endDate", "2017-12-22");      //结束时间


        Call<HttpResult<ListResult<HotelRoomShowModel>>> call = service.getHotelAvailableRoomTypeList(JsonUtils.convertParam("getHotelAvailableRoomTypeList", h1));
        call.enqueue(new CallbackImpl<ListResult<HotelRoomShowModel>>() {
            @Override
            public void responseSuccess(Call<HttpResult<ListResult<HotelRoomShowModel>>> call, Response<HttpResult<ListResult<HotelRoomShowModel>>> response) {

                if (response.body().getData() != null) {

                    if (groupTittles.size() > 0) {
                        groupTittles.clear();
                    }
                    groupTittles.addAll(response.body().getData().dataList);


                    if (groupDatas.size() > 0) {
                        groupDatas.clear();
                    }
                    for (HotelRoomShowModel groupItem : groupTittles) {
                        ArrayList<HotelRoomShowModel.HotelRoomTypeShowModel> itemList = (ArrayList<HotelRoomShowModel.HotelRoomTypeShowModel>) groupItem.roomPrice;
                        groupDatas.add(itemList);
                    }

                    selectHomeExpandableListAdapter.notifyDataSetChanged();

                }

            }
        });
    }

    /**
     * 获取修改订单的详细信息
     */
    private void toChangeBookOrder() {

        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("orderUuid", orderMainUuid);

        Call<HttpResult<ChangeOrderBean>> call = service.toChangeBookOrder(JsonUtils.convertParam("toChangeBookOrder", h1));
        call.enqueue(new CallbackImpl<ChangeOrderBean>() {
            @Override
            public void responseSuccess(Call<HttpResult<ChangeOrderBean>> call, Response<HttpResult<ChangeOrderBean>> response) {
                changeOrderBean = response.body().getData();
                if (changeOrderBean != null) {

                    if (changeOrderBean.hotelUuid != null) {
                        getHotelAvailableRoomTypeList(changeOrderBean.hotelUuid);
                    } else {
                        ToastUtil.showShortToast(mContext, "本酒店Uuid不存在");
                    }

                    changeUI();
                }
            }
        });


    }

    private void changeUI() {
        tvHotelName.setText(changeOrderBean.hotelName);
        tvTimeForSettleLeave.setText("入离店日期：" + changeOrderBean.getStartDate() + " - " + changeOrderBean.getEndDate() + "共" + changeOrderBean.inDayNum + "晚");
        tvHotelStyle.setText(changeOrderBean.roomTypeName + " | " + changeOrderBean.roomTypeDesc);
        tvOrderId.setText("订单编号： " + changeOrderBean.orderId);
        tvOrderPrice.setText(changeOrderBean.roomName + ": " + changeOrderBean.price + " | " + changeOrderBean.payStatusName);
    }

    private void initView() {
        groupTittles = new ArrayList<>();
        groupDatas = new ArrayList<>();
        // TODO: 2017/12/20 这里需要判断选择酒店是修改还是第一次选
        selectHomeExpandableListAdapter = new HotelDetailExpandableListAdapter(mContext);
        selectHomeExpandableListAdapter.setFrom(HotelDetailExpandableListAdapter.From_Change_Order);
        selectHomeExpandableListAdapter.setGroupData(groupDatas);
        selectHomeExpandableListAdapter.setGroupTittleData(groupTittles);
        elRooms.setAdapter(selectHomeExpandableListAdapter);

        // TODO: 2017/12/21 这里需要解决ependListView单选的问题  设置这个监听器不起作用
        elRooms.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {

                int groupCount = groupDatas.size();
                for (int g = 0; g < groupCount; g++) {
                    for (int c_item = 0; c_item < groupDatas.get(g).size(); c_item++) {
                        groupDatas.get(g).get(c_item).isSelected = false;
                    }
                }

                groupDatas.get(groupPosition).get(childPosition).isSelected = true;
                LogUtil.e("xyd", "被点击的条目是" + "group: " + groupPosition + "child:" + childPosition);
                selectHomeExpandableListAdapter.notifyDataSetChanged();
                return true;
            }
        });


    }

    @OnClick(R.id.btn_next)
    public void onViewClicked() {

        // 0 支付差价；  1 直接修改
        if (PayOrChange == 0) {
            changeBookOrder();
        } else if (PayOrChange == 1) {
            Intent intent2 = new Intent(mContext, CheckinDetailActivity.class);
            intent2.putExtra("mainUuid", orderMainUuid);
            startActivity(intent2);
        } else {
            // TODO: 2017/12/22 先计算差价
            calculateDiffAmout();
        }
//        Intent intent = new Intent(mContext, CheckinDetailActivity.class);
//        intent.putExtra("mainUuid", "");
//        intent.putExtra("detailUuid", "");
//        mContext.startActivity(intent);

    }

    private void changeBookOrder() {
        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("orderUuid", orderMainUuid);
        h1.put("startDate", "2017-12-22");
        h1.put("endDate", "2017-12-23");
        // TODO: 2017/12/22 暂时写死
        h1.put("roomTypeUuid", groupTittles.get(0).roomTypeUuid);
        h1.put("priceTypeUuid", groupTittles.get(0).roomPrice.get(0).priceTypeUuid);
        h1.put("balanceMoney", diffAmount + "");


        Call<HttpResult<SaveOrderChangeBean>> call = service.changeBookOrder(JsonUtils.convertParam("changeBookOrder", h1));
        call.enqueue(new CallbackImpl<SaveOrderChangeBean>() {
            @Override
            public void responseSuccess(Call<HttpResult<SaveOrderChangeBean>> call, Response<HttpResult<SaveOrderChangeBean>> response) {
                Intent intent = new Intent(mContext, PayPledgeActivity.class);
                intent.putExtra("fromPage", PayPledgeActivity.PayChangeOrder);
                intent.putExtra("saveOrderChangeBean", response.body().getData());
                mContext.startActivity(intent);
            }
        });

    }

    private void calculateDiffAmout() {
        HashMap<String, Object> h1 = new HashMap<>();
        h1.put("token", SharePrefUtil.getString(mContext, ShareKeys.Token, ""));
        h1.put("sessionId", SharePrefUtil.getString(mContext, ShareKeys.sessionId, ""));
        h1.put("orderUuid", orderMainUuid);
        // TODO: 2017/12/21 这里暂且写死
        h1.put("startDate", "2017-12-22");
        h1.put("endDate", "2017-12-23");
        h1.put("roomTypeUuid", groupTittles.get(0).roomTypeUuid);
        h1.put("priceTypeUuid", groupTittles.get(0).roomPrice.get(0).priceTypeUuid);

        Call<HttpResult<DiffAmountBean>> call = service.calculateDiffAmout(JsonUtils.convertParam("calculateDiffAmout", h1));
        call.enqueue(new CallbackImpl<DiffAmountBean>() {
            @Override
            public void responseSuccess(Call<HttpResult<DiffAmountBean>> call, Response<HttpResult<DiffAmountBean>> response) {
                diffAmount = response.body().getData().getBalanceMoney();
                if (diffAmount <= 0) {
                    // 不需要支付差价
                    PayOrChange = 1;
                    btnNext.setText("修改订单");
                } else {
                    // 需要支付差价
                    PayOrChange = 0;
                    btnNext.setText("支付差价");
                }
            }
        });
    }
}
